package com.yky.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.yky.service.sys.SysMenuService;
import com.yky.service.sys.SysPermissionService;
import com.yky.service.sys.SysRoleAccountService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.sso.clientA.config;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2024-02-21 11:04]
 * @copyright: 2024 echovin.com
 */

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Resource
    private SysRoleAccountService sysRoleAccountService;
    @Resource
    private SysMenuService sysMenuService;
    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器
        registry.addInterceptor(new SaInterceptor(handle -> {
            //角色校验
            Map<String, List<String>> rolesMatchMap = sysRoleAccountService.getUrlMappingRoles();
            Set<Map.Entry<String, List<String>>> entries = rolesMatchMap.entrySet();
            for (Map.Entry<String, List<String>> entry : entries){
                List<String> value = entry.getValue();
                String [] array = new String[value.size()];
                String[] result = value.toArray(array);
                SaRouter.match(entry.getKey(), s->StpUtil.checkRoleOr(result));
            }

            //权限校验
            List<String> urls = sysMenuService.getUrlList();
            for (String value : urls){
                SaRouter.match(value, s->StpUtil.checkPermission(value));
            }
        }));
    }

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }
}
